/**************************************************************
  > File Name: myDaemon.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年01月14日 星期五 19时54分56秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <errno.h>

#define FILENAME "/tmp/out"

static FILE *fp = NULL;

static int myDaemon()
{	
	pid_t pid;
	int fd;

	pid = fork();
	if (pid < 0)
	{
		perror("fork()");
		return -1;
	}
	if (pid > 0)
	{
		exit(0);
	}

	umask(0);
	setsid();
	chdir("/");

	fd = open("/dev/null",O_RDWR);
	if (fd < 0)
	{
		perror("open");
		return -1;
	}
	dup2(fd,0);
	dup2(fd,1);
	dup2(fd,2);
	if (fd > 2)
		close(fd);
	return 0;
}

void daemon_exit(int s)
{
	fclose(fp);
	closelog();
}

int main(int argc,char **argv)
{
	int i;
	
	/* 每次执行信号处理函数时3个信号都会被屏蔽，防止重复执行 */
	struct sigaction sa;
	sa.sa_handler = daemon_exit;
	sigemptyset(&sa.sa_mask);
	sigaddset(&sa.sa_mask, SIGINT);
	sigaddset(&sa.sa_mask, SIGQUIT);
	sigaddset(&sa.sa_mask, SIGTERM);
	sa.sa_flags = 0;
	
	sigaction(SIGINT, &sa, NULL);
	sigaction(SIGQUIT, &sa, NULL);
	sigaction(SIGTERM, &sa, NULL);

	openlog("myDaemon",LOG_PID,LOG_DAEMON);
	if (myDaemon())
	{
		syslog(LOG_ERR,"myDaemon() is failed!");
		exit(1);
	}
	else
	{
		syslog(LOG_INFO,"myDaemon is successded");
	}

	fp = fopen(FILENAME,"w");
	if (fp == NULL)
	{
		syslog(LOG_ERR,"fopen():%s",strerror(errno));
		exit(1);
	}
	syslog(LOG_INFO,"%s was opened",FILENAME);
	for (i = 0; ; i++)
	{
		fprintf(fp,"%d\n",i);
		fflush(fp);
		syslog(LOG_DEBUG,"%d is printed",i);
		sleep(1);
	}

	fclose(fp);
	closelog();

    exit(0);
}
